package com.qf.vote.controller;

import com.qf.vote.service.PhoneTokenService;
import com.qf.vote.service.TicketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class VotingWebSocket {

    static ConcurrentHashMap<String,Session> map = new ConcurrentHashMap<>();


    @Autowired
    PhoneTokenService phoneTokenService;

    /**
     * 当客户端发起webSocket连接时，服务器端，要进行逻辑处理，写在这个方法里
     */

    @OnOpen            //javax.webSocket
    public void onOpen(Session session) throws IOException {

        log.debug(" 连接成功");
        map.put(session.getId(),session);

    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.debug("客户端连接出问题了");
    }


    @OnClose
    public void onClose(Session session){
        map.remove(session.getId());
    }


    @Scheduled(cron = "0/3 * * * * ?")
    public void wsReturn() throws IOException, EncodeException {
        if (map!=null){
            long count = phoneTokenService.AllTicket();
            for (Map.Entry<String, Session> sessionEntry : map.entrySet()) {
                sessionEntry.getValue().getBasicRemote().sendObject(count);
            }
        }
    }
}
